import dayjs from "dayjs";
import SqLiteLog from "@/js_sdk/sqLite/log.js";

class LOG4J {
	static _wholeStore;
	constructor() {
		console.log("log4j");
	}

	static setLogVx(store) {
		this._wholeStore = store;
	}

	static getLogCat(fileName) {
		return {
			log: this.log.bind(this, fileName),
			error: this.error.bind(this, fileName),
		};
	}

	/**
	 * log 仅打印 日志不会记录
	 * @param 需要打印的消息
	 */
	static log(tag, ...message) {
		const date = dayjs();
		let strings = LOG4J.changeType(message);
		const log = `${date.format("YYYY-MM-DD")} ${date.format("HH:mm:ss.SSS")} [${tag}] LOG - ${strings}`;
		console.log(log);
		if (this._wholeStore) {
			this._wholeStore.dispatch("log4j/addLog", strings);
		}
		(({ message, date, strings }) => {
			SqLiteLog.insertData(tag, "LOG", message[0], strings, date.format("YYYY-MM-DD HH:mm:ss.SSS"), date.valueOf());
		})({
			message,
			date,
			strings,
		});
	}

	/**
	 * error 仅打印 日志不会记录
	 * @param 需要打印的消息
	 */
	static error(tag, ...message) {
		const date = dayjs();
		let strings = LOG4J.changeType(message);
		const log = `${date.format("YYYY-MM-DD")} ${date.format("HH:mm:ss.SSS")} [${tag}] ERROR - ${strings}`;
		console.error(log);
		if (this._wholeStore) {
			this._wholeStore.dispatch("log4j/addLog", strings);
		}
		(({ message, date, strings }) => {
			SqLiteLog.insertData(tag, "LOG", message[0], strings, date.format("YYYY-MM-DD HH:mm:ss.SSS"), date.valueOf());
		})({
			message,
			date,
			strings,
		});
	}

	static changeType(...message) {
		return message.map((msg) => {
			if (typeof msg === "string") {
				return msg;
			} else if (typeof msg === "array") {
				return "[" + msg.toString() + "]";
			} else if (typeof msg === "object" && !typeof msg === "function") {
				return JSON.stringify(msg);
			} else {
				return msg;
			}
		});
	}
}

export default LOG4J;
